<template>
    <div>
        <el-container>
            <el-header>
                <!-- 背景图 -->
                <div class="backgroundimg">
                    <el-image draggable="false" :src="singerinfo.artist.cover+'?param=1000y400'"  style="width:100%" ></el-image>
                </div>
                <!-- 头像 -->
                <div class="avatar">
                    <el-image  :src="singerinfo.artist.cover+'?param=240y240'"   ></el-image>
                </div>
                <!-- 姓名 -->
                <div class="name">
                   {{singerinfo.artist.name}}
                </div>
                <!-- 标签 -->
                <div class="tag">
                   {{singerinfo.identify.imageDesc}}
                </div>
                <!-- 作品 -->
                <div class="worksize">
                   <div>专辑:{{singerinfo.artist.albumSize}} {{"\u00A0"}}  单曲:{{singerinfo.artist.musicSize}}  {{"\u00A0"}}  MV:{{singerinfo.artist.mvSize}}</div>
                </div>
                <!-- 简介 -->
                <div class="briefDesc">
                   <span>{{singerinfo.artist.briefDesc}}</span>
                </div>
            </el-header>
            <el-main>
                <!-- 单曲 -->
                <div class="song-txt">热门单曲</div>
                <!-- loading -->
                <div v-if="loading" class="loading" v-loading="loading" ></div>
                <!-- 歌曲列表 -->
                <el-table
                class="musicTable"
                :data="musiclist"
                style="width: 100%"
                stripe
                fit
                v-if="!loading">
                <el-table-column
                    type="index" label="#" min-width="9%">
                </el-table-column>
                <el-table-column

                    label="歌曲名称"
                    min-width="35%">
                    <template v-slot='scope'>
                        <i v-if="play&&activeIndex===scope.$index" class="el-icon-video-pause" style="cursor: pointer;margin-right:3px" @click="broadcastMusic(scope.$index,scope.row,btnSt='stop')"> {{scope.row.title}}</i>
                        <i v-else class="el-icon-video-play" style="cursor: pointer;margin-right:3px" @click="broadcastMusic(scope.$index,scope.row,btnSt='broadcast')"> {{scope.row.title}} </i>
                        <!-- 通过判断url是否为空，判断歌曲是否可以播放 -->
                        <el-tag type="danger" size="mini" class="viptag" v-if="!scope.row.src">会员</el-tag>
                    </template>
                </el-table-column>
                <el-table-column
                    label="时长"
                    min-width="16%">
                    <template v-slot="scope">
                    {{scope.row.dt | dtFormat}}
                </template>
                </el-table-column>
                <el-table-column
                    label="操作"
                    min-width="24%">
                    <template v-slot="scope" >
                        <el-tooltip effect="light" content="下载" placement="top">
                            <el-button class="down_url" icon="el-icon-download" circle size="mini" @click="downloadSong(scope.row)"></el-button>
                        </el-tooltip>
                        <el-tooltip  effect="light" content="复制链接" placement="top">
                            <el-button   class="copy_url" icon="el-icon-document-copy" circle size="mini" @click="copySongUrl(scope.row)"></el-button>
                        </el-tooltip>

                </template>
                </el-table-column>
            </el-table>
            <!-- MV -->
            <div class="song-txt">MV</div>
            <!-- loading -->
                <div v-if="loading" class="loading" v-loading="loading" ></div>
            <div v-else class="mv">
                <div @click="linkTo(item.id)" class="mvlist" v-for="(item,index) in singermvlist" :key="index">
                    <!-- 封面 -->
                    <div class="mv-cover">
                        <el-image class="cover-img" :src="item.imgurl"></el-image>
                        <el-image class="broadcast-btn" src=""></el-image>
                     </div>
                    <!-- 名称 -->
                    <div class="mv-name">
                        {{item.name}}
                     </div>
                    <!-- 作者 -->
                    <div class="mv-artistName">
                        {{item.artistName}}
                     </div>
                </div>
            </div>

            </el-main>
            <el-footer></el-footer>
        </el-container>
        <!-- 播放器 -->
    <musicplayer @watch="watchplayer" :aplayerVisible="isShow" :musiclist='musiclist' :music="music" ref="musicplayer"></musicplayer>

    </div>
</template>

<script>
import MusicPlayer from '@/views/musicplayer'
// 引入复制组件
import Clipboard from 'clipboard'
// 引入下载文件组件
var Filesaver = require('file-saver')
export default {
  inject: ['reload'],
  components: {
    musicplayer: MusicPlayer
  },
  data () {
    return {
      // 歌手信息
      singerinfo: {
        //   设置这2个是因为不设置时，三层表达式元素渲染时找不到第2个对象，会报错解决办法是1、v-if不渲染元素，有值时再渲染 2、设置成2层，如下
        artist: {},
        identify: {}
      },
      //   歌曲列表
      music: {},
      musiclist: [],
      //   歌手mv
      singermvlist: [],
      //   控制播放按钮图标
      activeIndex: 0,
      play: false,
      //   控制播放器显示
      aplayerVisible: false,
      // 控制播放面板的展示与隐藏
      isShow: false,
      loading: false
    }
  },
  created () {
    //   歌手详情
    this.getSingerDetail()
    //   歌手单曲
    this.getSongs()
    // 歌手mv
    this.getSingerMV()
  },
  methods: {
    async getSingerDetail () {
      var singerid = this.$route.params.id
      const { data: res } = await this.$http.get('/artist/detail', { params: { id: singerid } })
      if (res.code !== 200) return this.$message.error('获取歌手详情失败')
      this.singerinfo = res.data
      console.log('this.singerDetail', this.singerinfo)
    },
    // 获取歌手歌曲
    async getSongs () {
      //   显示loading
      this.loading = true
      var singerid = this.$route.params.id
      const { data: res } = await this.$http.get('/artist/top/song', { params: { id: singerid } })
      if (res.code !== 200) return this.$message.error('获取歌手歌曲失败')
      this.musiclist = res.songs
      console.log('this.musiclist', this.musiclist)
      // 使用for循环将 artists 中的值转换为 artists.name
      this.musiclist.forEach(async item => {
        //   console.log('item:', item)
        // 歌曲名称
        item.title = item ? item.name : []
        // 歌曲作者
        item.artist = item.ar ? item.ar[0].name : []
        //   专辑名称
        item.albumname = item.al ? item.al.name : []
        //   歌曲封面
        item.pic = item.al ? item.al.picUrl : []
        //   获取歌曲id
        const songId = item.id
        //   歌曲url
        const songUrl = await this.getSongUrl(songId)
        // console.log('songUrl:', songUrl)
        item.src = songUrl
        //   获取歌词
        const songLrc = await this.getSongLrc(songId)
        item.lrc = songLrc
      })
      // 加上1s延时，解决for循环还没结束就渲染表格导致表格数据显示不全的问题
      setTimeout(() => {
        this.loading = false
      }, 1000)
    },
    // 歌手mv
    async getSingerMV () {
      var singerid = this.$route.params.id
      const { data: res } = await this.$http.get('/artist/mv', { params: { id: singerid } })
      if (res.code !== 200) return this.$message.error('获取歌手MV失败')
      this.singermvlist = res.mvs
      console.log('this.singermvlist', this.singermvlist)
    },
    // 获取歌曲链接
    async getSongUrl (songId) {
      const { data: res } = await this.$http.get('song/url', { params: { id: songId } })
      if (res.code !== 200) return this.$message.error('获取音乐链接失败')
      this.songUrl = res.data[0].url
      //   console.log('this.songUrl:', this.songUrl)
      return this.songUrl
    },
    // 通过 id 获取歌词
    async getSongLrc (songId) {
      const { data: res } = await this.$http.get('lyric', { params: { id: songId } })
      if (res.code !== 200) return this.$message.error('获取音乐歌词失败')
      try {
        var songLrc = res.lrc.lyric
        // console.log('songLrc:', songId, songLrc)
        // 如果歌词格式不对，不显示歌词
        if (songLrc.indexOf('[0') === -1) return '[00:00.000] (,,•́ . •̀,,) 抱歉，当前歌曲暂无歌词'
      } catch {
        // console.log('songLrc:', songId, songLrc)
        // 没有歌词时,显示 暂无歌词
        return '[00:00.000] (,,•́ . •̀,,) 抱歉，当前歌曲暂无歌词'
      }
      return songLrc
    },

    // 下载歌曲
    async downloadSong (scopeRow) {
    //   console.log(scopeRow)
      if (!scopeRow.src) return this.$message.error('这歌需要会员，你下不了')
      const songUrl = scopeRow.src
      const songName = scopeRow.title
      this.$notify({
        title: '下载',
        dangerouslyUseHTMLString: true,
        message: '<div>正在下载 <strong>' + songName + '</strong> ，请稍等...</div> ',
        type: 'success',
        duration: 2500
      })
      await Filesaver.saveAs(songUrl, songName + '.mp3')
    },
    // 复制歌曲链接
    async copySongUrl (scopeRow) {
      if (!scopeRow.src) return this.$message.error('这歌需要会员，你复制不了')
      const songUrl = 'https://music.163.com/song/media/outer/url?id=' + scopeRow.id + '.mp3 '
      //   console.log('触发了copySongUrl', songUrl)
      const clipboard = new Clipboard('.copy_url', {
        text: function () {
          return songUrl
        }
      })
      clipboard.on('success', e => {
        // console.log(e.text)
        this.$message.success(' 已复制到剪贴板！')
        clipboard.destroy()
      })
      clipboard.on('error', e => {
        e.clearSelection()
        clipboard.destroy()
      })
    },
    // 播放音乐
    broadcastMusic (index, scopeRow, btnSt) {
    //   console.log(scopeRow)
      if (!scopeRow.src) return this.$message.error('这歌需要会员，你听不了')
      // 显示播放器组件
      this.isShow = true
      // 控制播放/暂停icon的显示
      if (btnSt === 'broadcast') {
        this.activeIndex = index
        this.play = true
      } else {
        this.play = false
      }
      //   try catch 判断是否有currentMusic属性，并捕获异常
      try {
        //   判断是否有currentMusic属性，如果有执行暂停或播放选中的另外一首
        if (this.$refs.musicplayer.$refs.aplayer.currentMusic === scopeRow) {
          this.$refs.musicplayer.$refs.aplayer.toggle()
        } else {
          // 将当前currentMusic属性赋予新的song对象
          this.$refs.musicplayer.$refs.aplayer.currentMusic = scopeRow
          this.thenPlay()
        }
      } catch {
        //   如果没有currentMusic属性，执行播放方法
        this.music = scopeRow
        this.thenPlay()
      }
    },
    // 监听播放器 暂停和播放 事件，获得参数 activeIndex和play，控制歌曲列表中播放按钮的播放与暂停
    watchplayer (index, play) {
      console.log('watch', index, play)
      this.activeIndex = index
      this.play = play
    },
    // 通过nextTick方法，使播放器组件渲染完成后再执行play方法，防止报错,该play方法从vue-aplayer.vue方法中获得
    thenPlay () {
      this.$nextTick(() => {
        console.log(this.$refs.musicplayer.$refs.aplayer)
        this.$refs.musicplayer.$refs.aplayer.play()
      })
    },
    linkTo (mvid) {
      console.log('跳转详情页', mvid)
      this.$router.push({ path: `/video/videodetail/${mvid}` })
      //   跳转到详情页面时，回到顶部
      document.body.scrollTop = 0
      document.documentElement.scrollTop = 0
    }

  }
}
</script>

<style  scoped>
.el-header{
    /* border: 1px solid red; */
    min-height: 450px ;
}
.el-main{
    /* border: 1px solid black; */
    padding: 0 10%;
}
.el-footer{
    /* border: 1px solid green; */
    min-height: 200px;
}
/* 背景图片 */
.backgroundimg{
    /* 高斯模糊 */
    filter: blur(40px);
    /* 透明度 */
    opacity: 0.3;
    /* 隐藏溢出 */
    width: 100%;
    height: 450px;
    overflow: hidden;
    position: absolute;
    left: 0;
    top: 0;
    z-index: -1;
 }
/* 头像 */
.avatar{
    width: 210px;
    height: 210px;
    /* 父元素设置border-radius时，要加上overflow，否则不会有圆形效果 */
    border-radius: 50%;
    overflow: hidden;
    margin: 20px auto;
}
/* 姓名 */
.name{
    text-align: center;
    font-size: 20px;
    font-weight: 700;
}
/* 标签 */
.tag{
    margin-top: 5px;
    text-align: center;
    font-size: 15px;
    color: #333333;
}
/* 作品 */
.worksize{
    margin-top: 5px;
    text-align: center;
    font-size: 15px;
    color: #333333;
}
/* 简介 */
.briefDesc{
    font-size: 14px;
    margin: 5px auto;
    /* 设置文字单行 省略 */
    width: 60%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
.song-txt{
    font-size: 27px;
    margin-bottom: 10px;
}
/* loading样式 */
.loading{
    min-height: 100px;
}
/* mv */
.mv{
    display: flex;
    flex-wrap:wrap;
}
.mvlist{
    width: calc(16.66% - 20px);
    margin-left: 20px;
}

/* mv封面 */
.mv-cover{
    overflow: hidden;
    height: 60%;
    border-radius: 5px;
    position: relative;
}
/* 监听屏幕的宽度，当宽度小于1000px时，元素属性改变 */
    @media screen and (max-width:750px){
        .mvlist{
                width: calc(33.3% - 20px);

            }
        .mv-cover{
            height: 50%;
        }
        .down_url{
            font-size: 10px;
        }
        .copy_url{
            font-size: 10px;
        }
        }
.cover-img{
    height: 100%;
    transition: all 1s ease;
}
.mv-cover:hover .cover-img{
    transform: scale(1.1);
}
.mv-cover:hover .broadcast-btn{
    transform: translate(-50%,-50%) scaleX(1);
    /* 延时 */
    transition: all 0.5s ease 0s;
    opacity: 1;
    width: 40px;
    position: absolute;
    top: 50%;
    left: 50%;
}
/* 播放按钮图标 */
.broadcast-btn{
    opacity: 0;
     /* 延时 */
     transform: translate(-50%,-50%);
    transition: all 0.5s ease 0s;
    width: 1px;
    position: absolute;
    top: 50%;
    left: 50%;
}
/* mv名称 */
.mv-name{
    margin-top: 10px;
    font-size: 15px;
    color: #333333;
    font-weight: 700;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
}
/* mv作者 */
.mv-artistName{
    margin-top: 5px;
    font-size: 13px;
    color: #666666;
}

/* 播放器 固定在屏幕底部*/
#music-player{
    position: fixed;
    bottom: 0;
    width: 100%;
    /* height: 500; */
    left: 0;
}
</style>
